"""create standard file with license and meta tags (optionally add to hg)"""
# $Id: create.py 70fe0286d122 2013/07/17 05:39:39 pgurumur $
#
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# File generated on Sat Aug 25, 2012 @ 00:44:54

__version__  = "$Revision: 70fe0286d122 $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2013-07-17 05:39:39Z $"

import os
import sys
import datetime
import time
import shutil
import jinja2
import string
import random

from mercurial import commands, util

def printdate(value = 0):
   retval = None
   if value == 0:
      retval = datetime.datetime.now().strftime("%a, %B %d, %Y %T %p")
   elif value == 1:
      retval = datetime.datetime.now().strftime("%D %X")

   return retval

def randstring(value):
   return ''.join(random.choice(string.printable[0:63]) for ix in range(value))

def printenv(var):
   return os.getenv(var)

def create(ui, repo, *args, **opts):
   """
   Script to generate script file with proper license and RCS/CVS tags
   Languages supported are awk, c, cpp, lua, perl, python, sed, sh, sql and
   tcl. The template is written using Jinja. The new file is automatically
   added to mercurial repository

   Usage: hg create -l <language> file

   Example to generate a python script:
   hg create -l python myfirstscript.py

   if -m option is invoked, it would result in interpreter not being printed
   because the script would be treated as a module

   -s option is a default, should not be invoked ideally, because that would be
   used to source a different template

   if -p option is invoked, it should specify the version of the interpreter and
   this version would be appended to the interpreter name

   Example:
      hg create -l python -p 3.3 somefile.py

   Would result in the interpreter being #!/usr/bin/env python3.3
   The new template should have the following variable defined
   interpreter, date, year and name,
   name is the filename
   """

   cvspath = None
   hgpath = None
   repos = ui.configitems("repopath")
   template = ui.configitems("template")

   if repos and len(repos) == 2:
      cvspath = os.path.expandvars(repos[0][1])
      hgpath = os.path.expandvars(repos[1][1])

   if opts['template']:
      stdfile = opts['template']
   else:
      stdfile = os.path.expandvars(template[0][1])

   if not os.path.exists(stdfile):
      print("template file does not exist!")
      sys.exit(1)

   env = tmpl = None
   try:
      env = jinja2.Environment(loader = jinja2.FileSystemLoader(
         os.path.dirname(stdfile)))
      env.filters['date'] = printdate
      env.filters['randstring'] = randstring
      env.filters['env'] = printenv
      tmpl = env.get_template(os.path.basename(stdfile))
   except jinja2.exceptions.TemplateSyntaxError as err:
      print(err)
      sys.exit(1)

   tmplDict = {}
   tmplDict["year"] = time.strftime("%Y", time.localtime())
   if not opts['language']:
      print("no language defined, cannot create a file")
      sys.exit(1)

   if opts['language'] in ('py', 'python'):
      tmplDict["interpreter"] = "python"
   elif opts['language'] in ('pl', 'perl'):
      tmplDict["interpreter"] = "perl"
   elif opts['language'] in ('tcl', 'tk'):
      tmplDict["interpreter"] = "tclsh"
   elif opts['language'] in ('sh', 'shell'):
      tmplDict["interpreter"] = "sh"
   elif opts['language'] in ('awk'):
      tmplDict["interpreter"] = "awk"
   elif opts['language'] in ('sed'):
      tmplDict["interpreter"] = "sed"
   elif opts['language'] in ('c'):
      tmplDict["interpreter"] = "c"
   elif opts['language'] in ("cpp", "c++", "cc"):
      tmplDict["interpreter"] = "cpp"
   elif opts['language'] in ("lua"):
      tmplDict["interpreter"] = "lua"
   elif opts['language'] in ("sql"):
      tmplDict["interpreter"] = "sql"
   elif opts['language'] in ("html", "htm"):
      tmplDict["interpreter"] = "html"
   elif opts['language'] in ("js", "javascript"):
      tmplDict["interpreter"] = "javascript"
   elif opts['language'] in ('jinja', 'jinja2', 'j2'):
      tmplDict["interpreter"] = "jinja"
   elif opts['language'] in ("bc"):
      tmplDict["interpreter"] = "bc"
   elif opts['language'] in ("make", "gmake"):
      tmplDict["interpreter"] = "make"

   if opts['program']:
      tmplDict["version"] = opts['program']
   else:
      tmplDict["version"] = 0

   if opts['module']:
      tmplDict["module"] = 1
   else:
      tmplDict["module"] = 0

   for filename in args:
      if not os.path.exists(filename):
         tmplDict["name"] = filename
         with open(filename, "w") as fh:
            fh.write(tmpl.render(tmplDict))

         if not opts['remove']:
            path = util.expandpath(util.urllocalpath(os.getcwd()))
            commands.add(ui, repo, filename)
      else:
         print("%s already exists, will not be overridden" %filename)

cmdtable = {
      "create":   (create, [
         ('l', 'language', '', 'Type of programming language'),
         ('m', 'module', False, 'Enable templating for a module'),
         ('t', 'template', '', 'Template file to use'),
         ('p', 'program', '', 'Program version to use'),
         ('r', 'remove', False, 'Do not add file to repo'),
         ], "[options] filename")
      }
